package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneDepartment(department models.SysDepartment) error {
	return dao.DB.Create(&department).Error
}

func GetDepartmentList(queryInfo request.QueryInfo) (departments []models.SysDepartment, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Find(&departments).Error
		total = len(departments)
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysDepartment{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&departments).Error
	} else {
		if err = dao.DB.Model(&models.SysDepartment{}).Where("name like ?", "%"+queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("name like ?", "%"+queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&departments).Error
	}
	return
}

func GetAllDepartmentTree() (departmentTree []*models.SysDepartment, err error) {
	var major_list []models.SysMajor
	dao.DB.Find(&major_list)
	dao.DB.Find(&departmentTree)

	depart_major_map :=  make(map[int]*models.SysDepartment)
	for _, depart := range departmentTree{
		depart_major_map[depart.ID] = depart
	}

	for _, major := range major_list{
		depart_major_map[major.DepartmentID].Children = append(depart_major_map[major.DepartmentID].Children, major)
	}
	return
}

func UpdateDepartment(department models.SysDepartment) error {
	return dao.DB.Model(&models.SysDepartment{}).Where(&models.SysDepartment{ID:department.ID}).Update(&models.SysDepartment{Name:department.Name}).Error
}

func DeleteDepartment(id int) error {
	return dao.DB.Delete(&models.SysDepartment{ID:id}).Error
}
